package farmers.javcap.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

	
	// 如果文件存在，则追加内容；如果文件不存在，则创建文件
	public static void write(String fileName, String content) {
		FileWriter fw = null;
		try {
			File f = new File(fileName);
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println(content);
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// 获取http地址 "/" 最后的名称
	public static String getFileName(String httpUrl) {
		String[] split = httpUrl.split("/");
		return split[split.length-1];
	}
	
	// 获取http地址 "/" 最后的名称
	public static String getFileName2(String httpUrl) {
		String[] split = httpUrl.split("/");
		return split[split.length-2];
	}

    public static List<String> readFileContent(String fileName) {
        File file = new File(fileName);
        System.out.println("文件路径 " + file.getAbsolutePath());
        BufferedReader reader = null;
        List<String> list = new ArrayList<>();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                list.add(tempStr);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        System.out.println("文件内容 " + list);
        return list;
    }
}
